using System;
using System.Collections.Generic;
using System.Text;

namespace Neo4jRestSharp.Neo4jRestServices
{
	public class UriQueryBuilder
	{
		private readonly Dictionary<string, string> parameters = new Dictionary<string, string>();

		public void Add(string name, string value)
		{
			if (value != null)
			{
				value = Uri.EscapeDataString(value);
			}
			parameters.Add(name, value);
		}

		internal Uri AddToUri(Uri uri)
		{
			var str = ToString();
			if (str.Length > 1)
			{
				str = str.Substring(1);
			}
			var builder = new UriBuilder(uri);
			if ((builder.Query != null) && (builder.Query.Length > 1))
			{
				builder.Query = builder.Query.Substring(1) + "&" + str;
			}
			else
			{
				builder.Query = str;
			}
			return builder.Uri;
		}

		public override string ToString()
		{
			var builder = new StringBuilder();
			var flag = true;
			foreach (KeyValuePair<string, string> pair in parameters)
			{
				if (flag)
				{
					flag = false;
					builder.Append("?");
				}
				else
				{
					builder.Append("&");
				}
				builder.Append(pair.Key);
				if (pair.Value != null)
				{
					builder.AppendFormat("={0}", pair.Value);
				}
			}
			return builder.ToString();
		}
	}
}